<template>
  <div ref="fullscreenElement">
    <topHeader @examchangevalue="examchangevalue"></topHeader>
    <!-- <div class="header">
				<h3>{{examName}}-{{examInfo.coursesName}}</h3>
				 <span>模板管理</span>
				 <p>
					 <b @click="toggleFullscreen"><img src="../../assets/image/qp.png" alt="">{{ isFullscreen ? "退出全屏" : "全屏(F11)" }}</b>
					 <em @click="$router.push('/examoverview')">退出</em>
				 </p>
			 </div> -->
    <div class="tabNav">
      <div class="searchlist">
        <router-link :to="'/templateinformation?modelid=' + $route.query.modelid + '&nav6id=' + $route.query.nav6id"
          active-class="hover">模板信息及上传</router-link>
        <!-- <router-link to="/horizontalpositioning" active-class="hover">水平定位</router-link> -->
        <router-link :to="'/locationarea?modelid=' + $route.query.modelid + '&nav6id=' + $route.query.nav6id"
          active-class="hover">定位区</router-link>
        <router-link
          :to="'/admissionticketnumberarea?modelid=' + $route.query.modelid + '&nav6id=' + $route.query.nav6id"
          active-class="hover">准考证号区</router-link>
        <router-link :to="'/objectivequestion?modelid=' + $route.query.modelid + '&nav6id=' + $route.query.nav6id"
          active-class="hover">客观题区</router-link>
        <router-link :to="'/sbjectivequestion?modelid=' + $route.query.modelid + '&nav6id=' + $route.query.nav6id"
          active-class="hover">主观题区</router-link>
      </div>
      <div class="boxsetetid">
        <el-select v-model="pagevale" placeholder="请选择" @change="pagevalueindex">
          <el-option v-for="item in modelobj.templateImages" :key="item.page" :label="item.page" :value="item.page">
          </el-option>
        </el-select>
        <el-button @click="modelsave" v-preventReClick="2000">一键保存</el-button>
        <span @click="copymodelexam">复用其他考试模板</span>
      </div>
    </div>
    <div>
      <div class="cropperBox">
        <div class="cropperImageset">
          <ImageSelector ref="childComponent" @newRectangle="newRectangle" :drawStatus="drawStatus"
            :scorenumber="scorenumbers" :pagevale="pagevale" :imageUrllist="imgarray"
            @updateMarkList="handleUpdateMarkList" @modeltype="modeltype" :modelarealistcavans="modelarealistcavans"
            @smallpoints="smallpoints" @refreshdata="refreshdata" @editContent="editContent"
            @objbasicparameters="objbasicparameters" />
        </div>
        <div class="uploadcardInfo">
          <h3>{{ questiontype == 3 ? '缺考标记' : questiontype == 3 ? '条形码' : '考号填涂' }}-未完全框选</h3>
          <div>
            <span v-for="(item, index) in scorenumber" :class="scoreindex == index ? 'hover' : ''"
              @click="scoreindexclick(index, item)" :key="index">{{ item }}</span>
              <p style="cursor: pointer;" @click="scoreindexclick(-1,'缺考标记')">缺考标记</p>
          </div>
        </div>
      </div>
    </div>
    <!-- 创建复用考试 -->
    <examCopy v-if="examCopyIshow" @copyexamclick="copyexamclick" :type="2" :subjectidname="subjectidname"></examCopy>
    <!-- 自定义题号编辑弹窗 -->
    <el-dialog title="修改题号" :visible.sync="showQuestionDialog" width="400px" :close-on-click-modal="false">
      <el-form>
        <el-form-item label="请输入新的题号:">
          <el-input v-model="newQuestionInput" placeholder="请输入数字" type="number" @keyup.enter="wsOkBtn">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="wsEditBtn">取消</el-button>
        <el-button type="primary" @click="wsOkBtn">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import topHeader from '../../components/modeltop.vue'
import ImageSelector from '../../components/school/examnumberarea.vue'  //切图
import examCopy from '../../components/model/copysubject.vue'
import { saveModelSmallCaseImage, getitemcaseflagImage, getmodeldatae } from '../../api/api.js'
export default {
  name: 'App',
  data () {
    return {
      scorenumber: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
      scoreindex: -1,
      navbar: [
        {
          name: '模板信息及上传',
          id: 0,
        },
        {
          name: '水平定位',
          id: 1,
        },
        {
          name: '定位区',
          id: 2,
        },
        {
          name: '准考证号区',
          id: 3,
        },
        {
          name: '客观题区',
          id: 4,
        },
        {
          name: '主观题区',
          id: 5,
        }
      ],
      tabnavindex: 0,
      examclassify: '',
      examNumber: '',
      examNumberlist: [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22],
      cardNumber: 2,
      cardNumberlist: [2, 4, 6],
      cardColor: '',
      cardColorlist: ['黑色', '灰色', '彩色'],
      examdpi: '',
      examdpilist: [150, 200, 300],
      images: [],
      questiontype: '',
      questionList: [
        {
          name: '条形码',
          id: 4
        },
        {
          name: '考号填涂',
          id: 5
        },
        {
          name: '缺考标记',
          id: 3
        }
      ],

      selectradio: 1,
      fillinWidth: 0,
      fillinHeight: 0,
      intervalWidth: 0,
      intervalHeight: 0,
      modelobj: {
        id: 0,
        examId: 0,
        examCourseId: 0,
        examNoLength: 4,
        answerCardPages: 2,
        status: 0,
        templateImages: []
      },
      moduleImageurl: {},
      templateId: '',//模板id
      examCourseId: '',//考试科目id
      modeldata: {
        templateId: 0,
        examCourseId: 0,
        templateAreaType: 2
      },
      positioningare: {
        id: 0,
        templateId: 0,
        templateAreaType: 2,
        templateCuttingRegion: []
      },
      modeltypequestion: [],
      modelarealist: [],
      modelarealistcavans: [],
      classify: [],
      newtelept: [],
      editmodelishow: false,
      pagevale: 1,
      modelenews: [],
      typemodle: '',
      examName: '',
      options: [],
      editishow: false,
      examInfo: {},
      newvalelist: [],
      isFullscreen: false, // 当前是否处于全屏状态
      imgarray: [],
      newarryexamnumber: [],
      examCopyIshow: false,
      drawStatus: false,
      scorenumbers: '',
      wsarr: [], // WS的wxy坐标数组
      wsarr2: [], // 本地存储的wxy坐标数组
      wsObj: [], // WS新需求：遍历templateAreaType，把值一样的放在一个obj里
      // 自定义弹窗相关
      showQuestionDialog: false,
      newQuestionInput: '',
      currentEditData: null,
      targetPosition: -1,
      targetRegion: null
    }
  },
  mounted () {
    // 监听全屏状态变化
    this.modeltab()
    this.modelinfo()
    this.templateModelid = this.$route.query.modelid
    this.modelobj.templateImages = sessionStorage.getItem('imgarray') ? JSON.parse(sessionStorage.getItem('imgarray')) : []
    this.subjectidname = parseInt(this.$route.query.nav6id)
  },
  methods: {
    scoreindexclick (index, score) {
      this.scoreindex = index
      this.drawStatus = true
      this.scorenumbers = score
    },
    copymodelexam () {
      this.examCopyIshow = true
    },
    copyexamclick () {
      this.examCopyIshow = false
    },
    examchangevalue () {

    },
    modeltab () {
      let obj = {
        itemCaseflagid: this.$route.query.modelid
      }
      getitemcaseflagImage(obj).then(res => {
        this.imgarray = [
          { page: 1, url: res.obj.cardfront },
          { page: 2, url: res.obj.cardreverse }
        ]
      })
    },
    editContent (data) {
      // WS代码开始
      // 查看sessionStorage中的automaticRecognition数据
      // 提取外部的wxy坐标到wsarr数组
      this.wsarr = [
        {
          w: data.w,
          x: data.x,
          y: data.y
        }
      ]
      console.log('提取的外部wxy坐标数组wsarr:', this.wsarr[0])
      const automaticRecognition = sessionStorage.getItem('automaticRecognition')
      if (automaticRecognition) {
        const parsedData = JSON.parse(automaticRecognition)
        // 找到templateAreaType为3的客观题数据
        const objectiveData = parsedData.find(item => item.templateAreaType == 3)
        if (objectiveData && objectiveData.templateCuttingRegion) {
          const cuttingRegion = objectiveData.templateCuttingRegion[0]
          if (cuttingRegion && cuttingRegion.templateQuestion && cuttingRegion.templateQuestion.questionItems) {
            console.log('本地存储的includedNumbers:', cuttingRegion.templateQuestion.includedNumbers)
            console.log('当前编辑的题号:', data.includedNumbers)

            // 根据data.includedNumbers找到对应的题目
            const questionItem = cuttingRegion.templateQuestion.questionItems.find(
              item => item.questionNumber === data.includedNumbers
            )

            if (questionItem) {
              console.log('找到对应题目:', questionItem)
              // 提取该题目的wxy坐标
              this.wsarr2 = [
                {
                  w: questionItem.width,
                  x: questionItem.x,
                  y: questionItem.y
                }
              ]

            } else {

              // 如果没找到，使用传入的data
              this.wsarr2 = [
                {
                  w: data.w,
                  x: data.x,
                  y: data.y
                }
              ]
            }
          }
        }
      }

      // 对比
      if (this.wsarr.length > 0 && this.wsarr2.length > 0) {
        const data1 = this.wsarr[0]
        const data2 = this.wsarr2[0]

        // 对比w、x、y是否一致
        if (data1.w === data2.w && data1.x === data2.x && data1.y === data2.y) {
          console.log('✅ 坐标对比成功！wsarr和wsarr2的w、x、y坐标完全一致')
          console.log('一致的坐标值:', {
            w: data1.w,
            x: data1.x,
            y: data1.y
          })

          // 坐标对比成功后，先验证当前题号是否存在于本地includedNumbers中
          const automaticRecognition = sessionStorage.getItem('automaticRecognition')
          if (automaticRecognition) {
            const parsedData = JSON.parse(automaticRecognition)
            const objectiveData = parsedData.find(item => item.templateAreaType == 3)

            if (objectiveData && objectiveData.templateCuttingRegion) {
              const dataIncludedNumbers = data.includedNumbers // 当前编辑的题号，比如"6"
              console.log('当前编辑的题号:', dataIncludedNumbers)

              let foundPosition = -1
              let targetCuttingRegion = null

              // 遍历所有templateCuttingRegion，查找当前题号的位置
              for (let regionIndex = 0; regionIndex < objectiveData.templateCuttingRegion.length; regionIndex++) {
                const cuttingRegion = objectiveData.templateCuttingRegion[regionIndex]
                if (cuttingRegion.templateQuestion && cuttingRegion.templateQuestion.includedNumbers) {
                  const localIncludedNumbers = cuttingRegion.templateQuestion.includedNumbers
                  console.log(`区域${regionIndex}的includedNumbers:`, localIncludedNumbers)

                  // 检查当前题号是否在includedNumbers中存在
                  const numbersArray = localIncludedNumbers.split(',')
                  console.log('分割后的数组:', numbersArray)
                  console.log('当前题号类型:', typeof dataIncludedNumbers, '值:', dataIncludedNumbers)

                  // 确保类型一致性，将当前题号转为字符串进行比较
                  const currentNumberStr = String(dataIncludedNumbers)
                  const position = numbersArray.indexOf(currentNumberStr)

                  console.log('查找的字符串:', currentNumberStr, '查找结果位置:', position)

                  if (position !== -1) {
                    foundPosition = position
                    targetCuttingRegion = cuttingRegion
                    console.log(`✅ 找到题号${dataIncludedNumbers}在区域${regionIndex}的位置${position + 1}`)
                    break // 找到第一个匹配后立即退出循环，避免重复处理
                  }
                }
              }

              if (foundPosition !== -1 && targetCuttingRegion) {
                // 找到位置后，显示自定义弹窗让用户输入新的题号
                this.currentEditData = data
                this.targetPosition = foundPosition
                this.targetRegion = targetCuttingRegion
                this.newQuestionInput = ''
                this.showQuestionDialog = true
              } else {
                console.log('❌ 未找到对应的题号')
                this.$message.warning('未找到对应的题号，无法编辑')
              }
            }
          }
        } else {
          console.log('❌ 坐标对比失败')
          this.$message.warning('坐标对比失败，无法编辑')
        }
      }

      // WS代码结束
      this.editmodelishow = data.ishow
      let editcontent = this.modelarealist.templateCuttingRegion.filter(item => item.id == data.id)
      //console.info('编辑按钮被点击',editcontent)
      this.questiontype = data.templatePointType
      this.options = data.options
      this.positioningare.templateCuttingRegion = editcontent
      this.editishow = true
      // 保持原有的examNumber对象
      this.positioningare.id = editcontent[0].id
    },
    // WS代码开始
    wsOkBtn () {
      // 验证输入
      if (!this.newQuestionInput || !/^\d+$/.test(this.newQuestionInput)) {
        this.$message.error('请输入有效的数字')
        return
      }

      const newQuestionNumber = this.newQuestionInput.toString()

      // 检查targetRegion是否有效
      if (!this.targetRegion || !this.targetRegion.templateQuestion) {
        this.$message.error('数据异常，请重新操作')
        return
      }

      // 重新获取最新的automaticRecognition数据，确保引用正确
      const automaticRecognition = sessionStorage.getItem('automaticRecognition')
      if (automaticRecognition) {
        const parsedData = JSON.parse(automaticRecognition)
        const objectiveData = parsedData.find(item => item.templateAreaType == 3)

        if (objectiveData && objectiveData.templateCuttingRegion) {
          const dataIncludedNumbers = this.currentEditData.includedNumbers

          // 重新查找位置，确保数据是最新的
          for (let regionIndex = 0; regionIndex < objectiveData.templateCuttingRegion.length; regionIndex++) {
            const cuttingRegion = objectiveData.templateCuttingRegion[regionIndex]
            if (cuttingRegion.templateQuestion && cuttingRegion.templateQuestion.includedNumbers) {
              const localIncludedNumbers = cuttingRegion.templateQuestion.includedNumbers
              const numbersArray = localIncludedNumbers.split(',')
              const currentNumberStr = String(dataIncludedNumbers)
              const position = numbersArray.indexOf(currentNumberStr)

              if (position !== -1) {
                // 直接替换指定位置的题号
                numbersArray[position] = newQuestionNumber
                const newIncludedNumbers = numbersArray.join(',')

                // 更新数据
                cuttingRegion.templateQuestion.includedNumbers = newIncludedNumbers

                // 同时更新questionItems中对应的questionNumber
                const questionItems = cuttingRegion.templateQuestion.questionItems
                if (questionItems && questionItems.length > 0) {
                  const targetQuestionItem = questionItems.find(item => String(item.questionNumber) === currentNumberStr)
                  if (targetQuestionItem) {
                    targetQuestionItem.questionNumber = newQuestionNumber
                  }
                }

                // 更新sessionStorage
                sessionStorage.setItem('automaticRecognition', JSON.stringify(parsedData))

                this.$message.success(`题号已更新为: ${newQuestionNumber}`)

                // 打印更新后的本地includedNumbers
                console.log('更新后的includedNumbers:', cuttingRegion.templateQuestion.includedNumbers)

                // 复制一份数据进行API请求 - 直接使用已有的客观题数据
                const copyData = JSON.parse(JSON.stringify(objectiveData))
                if (copyData) {
                  saveModelSmallCaseImage(copyData).then(res => {
                    if (res.code == 0) {
                      this.$message.success('数据已同步到服务器');
                    } else {
                      this.$message.error(`同步失败: ${res.msg}`);
                    }
                  }).catch(error => {
                    console.error('API请求失败:', error)
                    this.$message.error('网络请求失败，请检查网络连接');
                  })
                }

                // 关闭弹窗并重置数据
                this.resetQuestionDialog()

                return
              }
            }
          }
        }
      }

      this.$message.error('更新失败，请重试')
    },
    // 重置题号编辑弹窗
    resetQuestionDialog () {
      this.showQuestionDialog = false
      this.newQuestionInput = ''
      this.currentEditData = null
      this.targetPosition = -1
      this.targetRegion = null
    },
    wsEditBtn () {
      console.log('用户取消了输入')
      // 关闭弹窗并重置数据
      this.resetQuestionDialog()
    },
    // WS代码结束
    questionchange (data) {
      // this.qiehuanzhiquestiontype = data
      this.positioningare.templateCuttingRegion[0].templatePointType = data
    },
    canceleditbox () {
      this.editishow = false
      this.editmodelishow = false
    },
    objbasicparameters () {
      this.editishow = false
      this.editmodelishow = false
    },
    smallpoints (data) {
      this.options = data
    },
    handleChange () {

    },
    modeltype (data) {
      this.typemodelssss = ''
      this.modeltypequestion.push(data)
      this.typemodelssss = data
    },
    handleUpdateMarkList (newVal) {
      this.newvalelist = newVal
      // 在这里处理从子组件传递过来的值
      // let newarray=newVal.filter(item => !item.id)
      // //console.info(newarray.length+'------')
      // 	// //console.info('dddd')
      // 	const currentTemplateId = this.modelobj.templateImages[this.pagevale - 1].templateId;
      // 	this.positioningare.templateCuttingRegion = newarray.map((item, index) => ({
      // 			id:0,
      // 			templateId:currentTemplateId, // 如果有具体的 templateId 值，可以在这里赋值
      // 			templatePointType:this.modeltypequestion[index], // 如果有具体的 templatePointType 值，可以在这里赋值
      // 			page:this.pagevale,
      // 			width: item.w,
      // 			height: item.h,
      // 			x: item.x,
      // 			y: item.y
      // 	}))
    },
    // 获取模板信息
    modelinfo (id) {
      // WS开始
      let obj = {
        itemCaseflagid: this.$route.query.modelid
      }
      getmodeldatae(obj).then(res => {
        console.info('res11111111111', res)
        // 遍历templateAreaType，把值一样的放在一个obj里
        if (res.code === 0 && res.obj && res.obj.templateCuttingRegion) {
          const templateCuttingRegion = res.obj.templateCuttingRegion
          // 清空并重新创建wsObj数据结构，避免重复添加
          this.wsObj = []
          const wsObj = []

          // 按templateAreaType分组
          const groupedByType = {}

          // 遍历templateCuttingRegion数组，按templateAreaType分组
          templateCuttingRegion.forEach(item => {
            const areaType = item.templateAreaType

            if (!groupedByType[areaType]) {
              groupedByType[areaType] = []
            }

            groupedByType[areaType].push(item)
          })

          // 为每个templateAreaType创建一个与res结构相同的对象
          Object.keys(groupedByType).forEach(areaType => {
            const obj = {
              id: 0,
              templateAreaType: parseInt(areaType),
              templateCuttingRegion: groupedByType[areaType],
              templateId: res.obj.templateId
            }
            wsObj.push(obj)
          })

          // 将wsObj保存到组件的data中和本地存储
          this.wsObj = wsObj
          sessionStorage.setItem('wsObj', JSON.stringify(wsObj))

          // 新需求：如果wsObj.length > 0才使用新逻辑，否则使用原先的automaticRecognition
          if (wsObj.length > 0) {
            sessionStorage.removeItem('automaticRecognition')
            sessionStorage.setItem('automaticRecognition', JSON.stringify(wsObj))
          } else {
            console.log('wsObj为空，保持原有automaticRecognition数据')
          }

        }

      })
      // WS结束
      if (sessionStorage.getItem('automaticRecognition')) {
        const mergedArray = JSON.parse(sessionStorage.getItem('automaticRecognition'))
        console.log('mergedArray,mergedArray', mergedArray);
        if (mergedArray.length != 0) {
          let newarry = mergedArray.filter(item => item.templateAreaType == 2)
          this.newarryexamnumber = newarry
          console.info(newarry)
          this.modelarealistcavans = newarry[0].templateCuttingRegion
            .filter(item => item.page === this.pagevale)
            .map(item => ({
              w: item.width,
              h: item.height,
              x: item.x,
              y: item.y,
              id: item.id,
              templatePointType: item.templatePointType,
              templateId: parseInt(this.templateModelid),
              options: (item.examNumber && item.examNumber.points || []).map(pointschilder => ({
                w: pointschilder.width || 0,
                h: pointschilder.height || 0,
                x: pointschilder.x || 0,
                y: pointschilder.y || 0,
                templateExamNumberId: pointschilder.templateExamNumberId || null
              }))
            }));
        }
      }
      return false
      //   this.modeldata.templateId = id||0

      post('/template/cuttingregion/area', this.modeldata)
        .then(res => {
          if (res.code == 200) {
            this.modelarealist = res.data
            if (res.data.templateCuttingRegion) {
              this.modelarealistcavans = res.data.templateCuttingRegion
                .filter(item => item.page === this.pagevale)
                .map(item => ({
                  w: item.width,
                  h: item.height,
                  x: item.x,
                  y: item.y,
                  id: item.id,
                  templatePointType: item.templatePointType,
                  // templateId:item.templateId||0
                }));
            } else {
              this.modelarealistcavans = []
            }
            // //console.info(this.modelarealistcavans)
          } else {
            this.$message.error(res.message);
          }
        })
      // .catch(error=>{
      //  this.$message.error(error.message); 
      // })
    },
    //   modelinfo(id){
    // 	  this.modeldata.templateId = id
    //   		  post('/template/cuttingregion/area',this.modeldata)
    //   		  .then(res=>{
    // 			  if(res.code==200){
    // 				  let imgid=this.modelenews[this.pagevale-1].id
    // 				  if (res.data && res.data.templateCuttingRegion !== null) {
    // 					  this.modelarealist = res.data
    // 					    this.modelarealistcavans = res.data.templateCuttingRegion
    // 					    .filter(item => item.page === this.pagevale)
    // 					    .map(item => ({
    // 					  	w: item.width,
    // 					  	h: item.height,
    // 					  	x: item.x,
    // 					  	y: item.y,
    // 					  	id:item.id,
    // 						templateImageid:imgid,
    // 						areaType:2,
    // 					  	templatePointType:item.templatePointType,
    // 					  	templateId:item.templateId,
    // 						options:(item.examNumber && item.examNumber.points || []).map(pointschilder=>({
    // 							 w: pointschilder.width || 0,
    // 							h: pointschilder.height || 0,
    // 							x: pointschilder.x || 0,
    // 							y: pointschilder.y || 0,
    // 							templateExamNumberId: pointschilder.templateExamNumberId || null
    // 						}))
    // 					  }));
    // 					   //console.info('Filtered and Mapped Data:', this.modelarealistcavans);
    // 				  }else{
    // 					  this.modelarealistcavans=[]
    // 				  }

    // 				// //console.info(this.modelarealistcavans)
    // 			  }else{
    // 				  this.$message.error(res.message); 
    // 			  }
    //   		  })
    //   		  // .catch(error=>{
    //   			 //  this.$message.error(error.message); 
    //   		  // })
    //   },
    refreshdata () {
      this.modeltab()
    },
    // 取消模板
    modeluploadcancel () {

    },
    zdsbmodel () {

    },
    async uploadData (item) {
      saveModelSmallCaseImage(item).then(res => {
        if (res.code == 0) {
          this.$message.success('保存成功');
        } else {
          this.$message.error(res.msg);
        }
      })
    },
    // 保存圈选区域
    modelsave () {
      console.info(sessionStorage.getItem('automaticRecognition'))
      if (sessionStorage.getItem('automaticRecognition')) {
        JSON.parse(sessionStorage.getItem('automaticRecognition')).forEach((item, index) => {
          this.uploadData(item)
        })
      }
      // this.positioningare.templateId = parseInt(this.templateModelid)
      // this.positioningare.templateAreaType = 1
      // saveModelSmallCaseImage(this.positioningare).then(res => {
      // 	if(res.code==0){
      // 		this.modelinfo( parseInt(this.templateModelid))
      // 		this.$message.success('保存成功'); 
      // 	}else{
      // 		this.$message.error(res.msg); 
      // 	}
      // })
    },
    // 保存圈选区域
    // modelsave(){
    // 	this.positioningare.templateId = parseInt(this.templateModelid)
    // 	// this.templateId = parseInt(this.templateModelid)
    // 	this.positioningare.templateAreaType = 2
    // 	console.info(this.positioningare)
    // 	// return false
    // 	// if(this.editishow){
    // 	// 	  // 保持原有的examNumber对象
    // 	// 	  const originalExamNumber = this.positioningare.templateCuttingRegion[0].examNumber || {};

    // 	// 	  // 更新examNumber，合并原有属性和新属性
    // 	// 	  this.positioningare.templateCuttingRegion[0].examNumber = {
    // 	// 	    ...originalExamNumber, // 保持原有属性
    // 	// 	    templateCuttingRegionId: originalExamNumber.templateCuttingRegionId || 0,
    // 	// 	    templateCuttingRegion: originalExamNumber.templateCuttingRegion || null,
    // 	// 	    arrangement: originalExamNumber.arrangement || 0,
    // 	// 	    points: originalExamNumber.points || [],
    // 	// 	    // 更新需要修改的值
    // 	// 	    optionArrangement: this.selectradio,
    // 	// 	    width: this.fillinWidth,
    // 	// 	    height: this.fillinHeight,
    // 	// 	    intervalWidth: this.intervalWidth,
    // 	// 	    intervalHeight: this.intervalHeight,
    // 	// 	    id: originalExamNumber.id || 0
    // 	// 	  }
    // 	// }
    // 	saveModelSmallCaseImage(this.newarryexamnumber[0]).then(res => {
    // 		if(res.code==0){
    // 			this.modelinfo( parseInt(this.templateModelid))
    // 			this.$message.success('保存成功'); 
    // 		}else{
    // 			this.$message.error(res.msg); 
    // 		}
    // 	})
    // },
    pagevalueindex (val) {
      this.pagevale = val
      this.modelinfo(this.templateId)
    },
    initDrag () {
      const draggableElement = this.$refs.childComponent.getDraggableElement();

      let isDragging = false; // 控制是否处于拖拽状态
      let offsetX = 0;
      let offsetY = 0;

      // 拖拽开始
      draggableElement.addEventListener('mousedown', (event) => {
        // 检查鼠标点击的位置是否在可交互元素上
        // const targetElement = event.target;
        // if (
        //   targetElement.tagName.toLowerCase() === 'input' ||
        //   targetElement.tagName.toLowerCase() === 'button' ||
        //   targetElement.tagName.toLowerCase() === 'a' ||
        //   targetElement.isContentEditable // 检查是否是可编辑内容
        // ) {
        //   // 如果点击的是可交互元素，不启动拖拽逻辑
        //   return;
        // }

        isDragging = true; // 标记拖拽开始
        offsetX = event.clientX - draggableElement.getBoundingClientRect().left;
        offsetY = event.clientY - draggableElement.getBoundingClientRect().top;

        // 禁用所有点击事件
        document.addEventListener('click', preventClick, { capture: true });

        document.addEventListener('mousemove', onDrag);
        document.addEventListener('mouseup', stopDrag);
      });

      // 拖拽逻辑
      const onDrag = (event) => {
        if (isDragging) {
          const x = event.clientX - offsetX;
          const y = event.clientY - offsetY;

          // 获取屏幕边界
          const screenWidth = window.innerWidth;
          const screenHeight = window.innerHeight;
          const elementWidth = draggableElement.offsetWidth;
          const elementHeight = draggableElement.offsetHeight;

          // 计算边界限制
          const minX = 0;
          const maxX = screenWidth - elementWidth;
          const minY = 0;
          const maxY = screenHeight - elementHeight;

          // 限制位置
          const clampedX = Math.max(minX, Math.min(maxX, x));
          const clampedY = Math.max(minY, Math.min(maxY, y));

          draggableElement.style.left = `${clampedX}px`;
          draggableElement.style.top = `${clampedY}px`;
        }
      };

      // 拖拽结束
      const stopDrag = () => {
        isDragging = false; // 标记拖拽结束

        // 恢复所有点击事件
        document.removeEventListener('click', preventClick, { capture: true });

        document.removeEventListener('mousemove', onDrag);
        document.removeEventListener('mouseup', stopDrag);
      };

      // 阻止点击事件的函数
      const preventClick = (event) => {
        event.preventDefault();
        event.stopPropagation();
      };
    },
    // 切换全屏
    toggleFullscreen () {
      if (!document.fullscreenEnabled) {
        alert("您的浏览器不支持全屏功能！");
        return;
      }

      if (this.isFullscreen) {
        // 退出全屏
        document.exitFullscreen();
        this.$refs.fullscreenElement.style.overflow = 'auto';
      } else {
        // 进入全屏
        this.$refs.fullscreenElement.requestFullscreen();
        this.$refs.fullscreenElement.style.overflow = 'auto';
      }
    },
    // 处理全屏状态变化
    handleFullscreenChange () {
      this.isFullscreen = !!document.fullscreenElement;
    },
    newRectangle(val) {
      console.info('vallist', val);
      if(this.scorenumbers === '缺考标记'){
        let option ={
          examNumber:null,
          height:val.h,
          width:val.w,
          x:val.x,
          y:val.y,
          id:0,
          page:1,
          templateId:this.$route.query.modelid,
          templatePointType:3,
          templateQuestion:null
        }
        const newArray = JSON.parse(JSON.stringify(this.newarryexamnumber[0]));
        newArray.templateCuttingRegion.push(option)
        const automaticRecognition = JSON.parse(sessionStorage.getItem('automaticRecognition') || '[]');
        // 找到 sessitem 中 templateAreaType 与 newArray 相等的项
        const index = automaticRecognition.findIndex(item => item.templateAreaType === newArray.templateAreaType);
        // 如果找到匹配项，替换整个对象
        if (index !== -1) {
          automaticRecognition[index] = newArray;
        }
        console.log('sessitem',automaticRecognition);
        sessionStorage.setItem('automaticRecognition', JSON.stringify(automaticRecognition));
      }else{
        const newArray = JSON.parse(JSON.stringify(this.newarryexamnumber[0]));
        
        newArray.templateCuttingRegion.forEach((item, index) => {
          if (item.examNumber && item.examNumber !== null && item.examNumber !== undefined) {
            // 确保 points 是一个数组
            if (!Array.isArray(item.examNumber.points)) {
              item.examNumber.points = [];
            }
            // 添加新的点
            item.examNumber.points.push({
              x: val.x, 
              y: val.y, 
              width: val.w, 
              height: val.h, 
              value: this.scorenumbers
            });
            item.examNumber.points.sort((a, b) => {
              // 先按 value 排序
              if (a.value !== b.value) {
                return a.value - b.value;
              }
              // 如果 value 相同，再按 x 坐标排序
              if (a.x !== b.x) {
                return a.x - b.x;
              }
              // 如果 x 也相同，最后按 y 坐标排序
              return a.y - b.y;
            });
          }
        });
        // 更新 this.newarryexamnumber
        // this.newarryexamnumber = newArray;
        console.info('newArray', newArray);
        const automaticRecognition = JSON.parse(sessionStorage.getItem('automaticRecognition') || '[]');
        // 找到 sessitem 中 templateAreaType 与 newArray 相等的项
        const index = automaticRecognition.findIndex(item => item.templateAreaType === newArray.templateAreaType);
        // 如果找到匹配项，替换整个对象
        if (index !== -1) {
          automaticRecognition[index] = newArray;
        }
        console.log('sessitem',automaticRecognition);
        sessionStorage.setItem('automaticRecognition', JSON.stringify(automaticRecognition));
      }
    }
  },
  watch: {
    newvalelist: {
      handler (val, old) {
        console.info('val-test', val)
        console.info('val-test', this.newarryexamnumber)
        // 1. 提取 newVal 中没有 id 的对象
        // const itemsWithoutId = val.filter((item) => !item.id);
        // if(itemsWithoutId.length>0){
        // 	const currentTemplateId = parseInt(this.templateModelid);
        // 	this.positioningare.templateCuttingRegion = itemsWithoutId.map((item, index) => ({
        // 			id:0,
        // 			templateId:currentTemplateId, // 如果有具体的 templateId 值，可以在这里赋值
        // 			templatePointType:this.modeltypequestion[index], // 如果有具体的 templatePointType 值，可以在这里赋值
        // 			page:this.pagevale,
        // 			width: item.w,
        // 			height: item.h,
        // 			x: item.x,
        // 			y: item.y
        // 	}))
        // 	setTimeout(()=>{
        // 		let updatedOptions = this.options.map(option => ({
        // 			  ...option, // 展开原始对象，保留其所有属性
        // 			  templateExamNumberId: 2 // 添加新的属性并赋值
        // 			}));
        // 			this.positioningare.templateCuttingRegion.map((item,index)=>{
        // 				if(item.templatePointType==5){
        // 					this.positioningare.templateCuttingRegion[index].examNumber={
        // 						id: 0,
        // 						templateCuttingRegionId:2,
        // 						optionArrangement:this.selectradio,
        // 						width:this.fillinWidth,
        // 						height:this.fillinHeight,
        // 						intervalWidth:this.intervalWidth,
        // 						intervalHeight:this.intervalHeight,
        // 						points:updatedOptions
        // 					}
        // 				}
        // 			})
        // 	},2000)
        // 	return false
        // }
        // let imgid=this.modelenews[this.pagevale-1].id
        // const findDifferences = (arr1, arr2) => {
        //   return arr1.filter((item1, index) => {
        // 	const item2 = arr2[index];
        // 	return (
        // 	  item1.w !== item2.width ||
        // 	  item1.h !== item2.height ||
        // 	  item1.x !== item2.x ||
        // 	  item1.y !== item2.y
        // 	);
        //   });
        // };
        // const differences = findDifferences(val, this.modelarealist.templateCuttingRegion);
        // if(differences.length>0){
        // 	//console.info(differences)
        // 	// const parsedArray = differences[0].map(str => {
        // 	//   const [x, y, width, height] = str.split(', ').map(Number);
        // 	//   return { x, y, width, height };
        // 	// });
        // 	const parsedArray = differences[0].options.map(item => ({
        // 	  width: item.w,       // 将 w 改为 width
        // 	  height: item.h,      // 将 h 改为 height
        // 	  x: item.x,           // 保留 x
        // 	  y: item.y,           // 保留 y
        // 	  templateExamNumberId:differences[0].id// 添加新属性
        // 	}));
        // 	this.positioningare.templateCuttingRegion = differences
        // 	this.positioningare.id=differences[0].id
        // 	if(differences[0].templatePointType==5){
        // 		this.positioningare.templateCuttingRegion[0] = {
        // 			id:differences[0].id,
        // 			templateId:parseInt(this.templateModelid), // 如果有具体的 templateId 值，可以在这里赋值
        // 			templatePointType:differences[0].templatePointType, // 如果有具体的 templatePointType 值，可以在这里赋值
        // 			page:this.pagevale,
        // 			width: differences[0].w,
        // 			height: differences[0].h,
        // 			x: differences[0].x,
        // 			y: differences[0].y,	
        // 		}
        // 		  this.positioningare.templateCuttingRegion[0].examNumber = {
        // 			templateCuttingRegionId: differences[0].templateCuttingRegionId || 0,
        // 			templateCuttingRegion: differences[0].templateCuttingRegion || null,
        // 			arrangement: differences[0].arrangement || 0,
        // 			points: parsedArray || [],
        // 			// 更新需要修改的值
        // 			optionArrangement: this.selectradio,
        // 			width: this.fillinWidth,
        // 			height: this.fillinHeight,
        // 			intervalWidth: this.intervalWidth,
        // 			intervalHeight: this.intervalHeight,
        // 			id: differences[0].id || 0
        // 		  }
        // 	}else{
        // 		this.positioningare.templateCuttingRegion = differences.map((item, index) => ({
        // 			id: item.id,
        // 			templateId:parseInt(this.templateModelid), // 如果有具体的 templateId 值，可以在这里赋值
        // 			templatePointType:item.templatePointType, // 如果有具体的 templatePointType 值，可以在这里赋值
        // 			page:this.pagevale,
        // 			width: item.w,
        // 			height: item.h,
        // 			x: item.x,
        // 			y: item.y
        // 		}))
        // 	}
        // }
        // console.info(this.positioningare)
      },
      deep: true
    }
  },
  components: {
    ImageSelector, topHeader, examCopy
  },
  beforeRouteLeave (to, from, next) {
    if (this.telemplatelist && this.modelarealist.templateCuttingRegion) {
      if (this.newvalelist.length != this.modelarealist.templateCuttingRegion.length) {
        // 如果数组不同，阻止跳转并提示用户
        this.$confirm('有未保存的操作，是否继续', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          next();
        }).catch(() => {
          next(false);
        });
        next(false); // 阻止跳转
      } else {
        // 如果数组长度相同，比较数组中的每个元素
        const isSame = this.newvalelist.every((item, index) => {
          const modelarealistItem = this.modelarealist.templateCuttingRegion[index];
          return item.w === modelarealistItem.width
            && item.h === modelarealistItem.height
            && item.x === modelarealistItem.x
            && item.y === modelarealistItem.y
            && item.templatePointType === modelarealistItem.templatePointType;
        });
        if (isSame) {
          // 如果所有元素都相同，直接跳转
          next();
        } else {
          // 如果有任何一个元素不同，阻止跳转并提示用户
          this.$confirm('有未保存的操作，是否继续', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            next();
          }).catch(() => {
            next(false);
          });
          next(false); // 阻止跳转
        }
      }
    } else {
      next()
    }
  }
}
</script>

<style scoped>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  text-align: center;
  color: #2c3e50;
}

.header {
  padding: 0 40px;
  height: 48px;
  padding: 0 24px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #fff;
  background: #2379F6;
  font-size: 16px;
}

.header h3 {
  font-weight: normal;
  font-size: 16px;
}

.header p {
  display: flex;
}

.header p b {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 134px;
  height: 32px;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 17px;
  border: 1px solid #FFFFFF;
  text-align: center;
  line-height: 32px;
  cursor: pointer;
  margin-right: 14px;
}

.header p b img {
  width: 16px;
  margin-right: 8px;
}

.header p em {
  display: inline-block;
  width: 76px;
  height: 32px;
  background: #FFFFFF;
  border-radius: 17px;
  border: 1px solid #FFFFFF;
  color: #2379F6;
  text-align: center;
  line-height: 32px;
  cursor: pointer
}

.tabNav {
  padding: 0 40px;
  height: 54px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 24px 0 10px;
  background: #fff;
}

.tabNav ul {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.tabNav ul li {
  padding: 0 20px;
  cursor: pointer;
  line-height: 38px;
  color: #557292;
  position: relative
}

.tabNav ul li:hover,
.tabNav ul li.hover {
  color: #2A303B;
}

.tabNav ul li:hover::after,
.tabNav ul li.hover::after {
  content: '';
  width: 24px;
  height: 4px;
  background: #295CFF;
  border-radius: 2px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0
}

.tabNav span {
  display: inline-block;
  width: 140px;
  height: 34px;
  background: #F2F6FB;
  border-radius: 10px;
  border: 1px solid #295CFF;
  font-weight: 500;
  font-size: 14px;
  color: #295CFF;
  text-align: center;
  line-height: 34px;
  cursor: pointer;
}

/* 上传 */
.uploadMarks {
  box-sizing: border-box;
  background: #F4F7FD;
  width: 100vw;
  height: calc(100vh - 102px);
  position: relative;
}

.smcsbutton {
  width: 124px;
  height: 34px;
  background: #2379F6;
  border-radius: 10px;
  font-size: 14px;
  color: #FFFFFF;
  text-align: center;
  border: none;
  /* margin:24px 0 0 24px; */
  position: absolute;
  padding: 0;
  left: 24px;
  top: 24px;
}

.boxcenter {
  display: flex;
  justify-content: space-between;
}

.uploadcardInfo {
  width: 290px;
  height: calc(100vh - 102px);
  background: #fff;
  position: relative
}

.uploadcardInfo div {
  padding: 10px;
}

.uploadcardInfo div span {
  display: inline-block;
  width: 24px;
  height: 24px;
  border-radius: 4px;
  background: #E8F3FF;
  text-align: center;
  line-height: 24px;
  color: #165DFF;
  margin-right: 10px;
  margin-bottom: 10px;
  cursor: pointer;
}

.uploadcardInfo div span.hover,
.uploadcardInfo div span:hover {
  background: #D54941;
  color: #fff;
}

.examboxbutton {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 54px;
  background: #E8F0FA;
  position: absolute;
  left: 0;
  bottom: 0;
}

.examboxbutton>>>.el-button {
  width: 124px;
  height: 34px;
  border-radius: 10px;
  padding: 0;
  margin: 0;
  font-size: 12px;
  border: 1px solid #295CFF;
  color: #295CFF;
  background: none;
}

.examboxbutton>>>.el-button:first-child {
  background: #295CFF;
  border: 1px solid #295CFF;
  color: #fff;
}

.examboxbutton>>>.el-button:nth-child(2) {
  margin: 0 8px;
}

.examboxbutton1 {
  width: 100%;
  box-sizing: border-box;
  display: flex;
  align-items: center;
  padding: 0 15px;
  height: 54px;
  background: #E8F0FA;
  position: absolute;
  left: 0;
  bottom: 0;
  justify-content: center;
}

.examboxbutton1>>>.el-button {
  width: 124px;
  height: 34px;
  border-radius: 10px;
  padding: 0;
  margin: 0;
  font-size: 12px;
  border: 1px solid #295CFF;
  color: #295CFF;
  background: none;
}

.examboxbutton1>>>.el-button:first-child {
  background: #295CFF;
  border: 1px solid #295CFF;
  color: #fff;
}

.examboxbutton1>>>.el-button:nth-child(2) {
  margin: 0 8px;
}

.uploadcardInfo h3 {
  line-height: 67px;
  border-bottom: solid 1px #D8E4F0;
  padding: 0 24px;
  color: #2A303B;
  font-weight: normal
}

.uploadcardInfo ul li {
  display: flex;
  align-items: center;
  color: #8E96A4;
  font-size: 16px;
  padding: 0 24px;
  margin-top: 24px;
}

.uploadcardInfo ul li span {
  color: #8E96A4;
  width: 120px;
}

.uploadcardInfo ul li>>>.el-input__inner {
  border-radius: 10px;
}

.uploadcardInfo ul li>>>.el-textarea {
  width: calc(100% - 26px)
}

.uploadCardimage {
  width: calc(100% - 460px);
  height: calc(100vh - 102px);
  display: flex;
  justify-content: center;
  align-items: center;
  flex-wrap: wrap;
  position: relative;
}

.uploadCardimage span {
  display: block;
  width: 100%;
  text-align: center;
}

.uploaddiv {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
}

.uploaddivattention {
  font-size: 14px;
  color: #B3B8C2;
}

.cropperBox {
  height: calc(100vh - 104px);
  display: flex;
}

.cropperImageset {
  width: 100%;
  height: calc(100vh - 104px);
  overflow: scroll;
  position: relative
}

.routate {
  position: absolute;
  left: 50px;
  top: 5px;
  background: #fff;
  height: 60px;
  display: flex;
  align-items: center;
  padding: 0 10px 0 0;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
  border-radius: 5px;
  font-size: 14px;
  color: #557292;
  border-radius: 10px;
  z-index: 10
}

.routate>>>.el-select,
.routate>>>.el-input {
  width: 150px;
}

.routate>>>.el-select {
  margin-right: 10px;
}

.routate>>>.el-input {
  margin-left: 10px;
  margin-right: 10px;
}

.routate>>>.el-button {
  border-radius: 10px;
  height: 35px;
  width: 55px;
  padding: 0;
  margin-left: 10px
}

.routate>>>.el-input__inner {
  border-radius: 10px;
  height: 35px;
}

.image-preview img {
  box-sizing: border-box;
  width: 150px;
  height: 150px;
  background: #FFFFFF;
  border-radius: 10px;
  text-align: center;
  font-size: 16px;
  color: #295CFF;
  cursor: pointer;
  margin: 22px;
}

.searchlist {
  box-sizing: border-box;
  width: auto;
  padding: 0 40px;
  display: flex;
  justify-content: space-between;
  height: 54px;
  background: #FFFFFF;
  border-radius: 10px;
  padding: 0 24px;
  align-items: center;
}

.searchlist {
  padding-left: 20px;
  display: flex;
  align-items: center;
  justify-content: left;
}

.searchlist a {
  display: block;
  color: #557292;
  font-size: 14px;
  /* width:100px; */
  text-align: center;
  position: relative;
  line-height: 52px;
  padding: 0 15px;
}

.searchlist a:hover,
.searchlist a.hover {
  color: #295CFF;
}

.searchlist a:hover::after,
.searchlist a.hover::after {
  content: '';
  width: 24px;
  height: 4px;
  background: #295CFF;
  border-radius: 2px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
  bottom: 0;
}

.boxsetetid {
  display: flex;
  align-items: center;
}

.boxsetetid>>>.el-input__inner {
  width: 90px;
  height: 34px;
  border-radius: 10px;
  border: 1px solid #295CFF;
  font-weight: 500;
  font-size: 14px;
  color: #295CFF;
}

.boxsetetid>>>.el-select .el-input .el-select__caret {
  color: #295CFF
}

.boxsetetid>>>.el-input__icon {
  line-height: 34px;
}

.boxsetetid>>>.el-button {
  padding: 0;
  width: 96px;
  height: 34px;
  background: #295CFF;
  border-radius: 10px;
  color: #fff;
  line-height: 34px;
  margin: 0 10px;
}

.breadBox>>>.el-breadcrumb__inner a,
.breadBox>>>.el-breadcrumb__inner.is-link {
  font-weight: normal
}

.breadBox>>>.el-breadcrumb__item:last-child .el-breadcrumb__inner,
.breadBox>>>.el-breadcrumb__item:last-child .el-breadcrumb__inner a,
.breadBox>>>.el-breadcrumb__item:last-child .el-breadcrumb__inner a:hover,
.breadBox>>>.el-breadcrumb__item:last-child .el-breadcrumb__inner:hover {
  font-weight: bold
}
</style>